package com.ismarkendenis.dxkeyexchange;

import java.math.BigInteger;
import java.nio.charset.Charset;

public class CBCCipher 
{
	private static final int BLOCKSIZE = 32;
	
	public String decrypt(String fileName, BigInteger gabp)
	{
		Reader reader = new Reader();
		ShaSum shasum = new ShaSum();
		
		byte[] encryptedFile = reader.readFile(fileName);
		byte[] key           = shasum.shaSumKey(gabp);
		
		int nrOfBlocks   = encryptedFile.length / BLOCKSIZE ;
		
		StringBuilder finalText = new StringBuilder();
		
		String previousEncryptedString = "";
		String keyString = new String(key, Charset.forName("ISO-8859-1"));
		
		// For each block
		for (int i = 0; i < nrOfBlocks; i++)
		{
			String encryptedString = (new String(encryptedFile, Charset.forName("ISO-8859-1")).substring(i * BLOCKSIZE, (i + 1) * BLOCKSIZE));
			String result = "";
			
			for (int c = 0; c < BLOCKSIZE; c++)
			{
				result += (char)(keyString.charAt((BLOCKSIZE-1)  - c) ^ encryptedString.charAt(c));
			}
			
			if (i > 0)
			{
				String temp = "";
				for (int c = 0; c < BLOCKSIZE; c++)
				{
					temp += (char)(result.charAt(c) ^ previousEncryptedString.charAt(c));
				}
				result = temp;
			}
			
			previousEncryptedString = encryptedString;
			
			finalText.append(result);
		}
		
		return finalText.toString();
	}
}